<template>
  <!-- <h2>对账日历</h2> -->
  <div class="reconciliation-wrapper">
    <div class="left-info">
      <div class="calendarday">
        <calendarday :isActive="isActive" @getDays="getDay"></calendarday>
      </div>
      <div class="bill-info">
        <div>本月</div>
        <div class="layout">
          <span>欠款</span>
          <span>{{ setThousandBit(ownSumMoney) }}</span>
        </div>
        <div class="layout">
          <span>新增欠款</span>
          <span>{{ setThousandBit(newAddOwnSumMoney) }}</span>
        </div>
        <div class="layout">
          <span>现金流入</span>
          <span>{{ setThousandBit(topUpSumMoney) }}</span>
        </div>
        <div class="layout">
          <span>诊疗服务收入</span>
          <span>{{ setThousandBit(payOrderSumMoney) }}</span>
        </div>
        <div class="layout">
          <span>余额充值</span>
          <span>{{ setThousandBit(onlyTopUpBalanceSumMoney) }}</span>
        </div>
      </div>
    </div>
    <div class="right-info">
      <div class="chart">
        <div ref="type" style="width: 1000px; height: 270px;"></div>
      </div>
      <div class="calendar-detail">
        <div class="calendar-date">
          <span>{{currentDate}} {{weekday}}</span>
        </div>
        <div class="calendar-content">
            <calendar-detail-item v-for="item in caledarList" :objData="item"></calendar-detail-item>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang='ts'>
import { defineComponent, ref, onMounted, inject, reactive, toRefs, watch } from '@vue/runtime-core'
import { ElMessage } from 'element-plus'
import calendarday from '../../components/calendarday.vue'
import calendarDetailItem from '../../components/calendarDetailItem/calendarDetailItem.vue'
import { getNowDates } from '../../utils/nowDate'
import { getAllDays } from '../../utils/Date'
import { setThousandBit } from "../../usefn/getSeparation"
import useRequest from "../../hook/request"

export default defineComponent({
  name: 'ReconciliationCalendar',
  components: {
    calendarday,
    calendarDetailItem
  },
  setup() {
    const type = ref<HTMLElement>()
    const isActive = ref('day')
    const weekday = ref('')
    const currentDate = ref('')
    const currentTime = ref(0)
    let echarts: any = inject("echart");
    let weeks = ['星期天','星期一','星期二', '星期三','星期四','星期五','星期六']
    let startTime = ref('')
    let endTime = ref('')
    let monthDateStart = ref('')
    let monthDateEnd = ref('')
    let resultDate = ref('')
    onMounted(async() => {
      let result = getNowDates()
      currentTime.value = new Date(result).getTime()
      let dates = result.split('-')
      let res = new Date(result).getDay()
      weekday.value = weeks[res]
      currentDate.value = `${dates[1]}月${dates[2]}日`
      monthDateStart.value = `${dates[0]}-${dates[1]}-01`
      monthDateEnd.value = result
      resultDate.value = result

      await getEightDayData(result)
      await getMonthDate()
      await getDetailByDay()
      
      
      

    })
    const setEchartDate = () => {
      let myChart = echarts.init(type.value);
      let option = {
        color: ['#11b9d0', '#e1bee7','#409eff', '#fac858'],
        tooltip: {
        trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#409eff'
            }
          }
        },
        legend: {
            right: 10,
            top: 10,
            data: ['收款金额', '现金流入', '诊疗服务收入', '新增欠款'],
            padding: 5
        },
        series:[
          { 
            type: 'bar',
            name: '收款金额',
            data: <number[]>[],
          },
          { 
            type: 'bar',
            name: '现金流入',
            data: <number[]>[],
          },
          { 
            type: 'bar',
            name: '诊疗服务收入',
            data: <number[]>[],
          },
          { 
            type: 'line',
            name: '新增欠款',
            data: <number[]>[],
          }
        ],
        xAxis: {
          type: 'category',
          data: <string[]>[]
        },
        yAxis: {
          type: 'value'
        },
      }
      
      detailByDay.value.shift()
      detailByDay.value.forEach((item:any) => {
        option.series[0].data.push(item.orderTopSumMoney)
        option.series[1].data.push(item.topUp)
        option.series[2].data.push(item.orderSumMoney)
        option.series[3].data.push(item.OwnSumMoney)
        option.xAxis.data.push(setSWitch(item.dayStr))
      })
    
      myChart.setOption(option)
    }
    const setSWitch = (date: string) => {
      let data = ''
      let res = date.split('-')
      data = `${res[1]}月${res[2]}日`
      return data
    }
    
    const getDay = (data: string) => {
      resultDate.value = data
      let selectDateTime = new Date(data).getTime()
      if(selectDateTime > currentTime.value) {
        ElMessage.warning('请注意当前选中的时间大于今天')
      }
      let dates = data.split('-')
      let res = new Date(data).getDay();
      weekday.value = weeks[res]
      currentDate.value = `${dates[1]}月${dates[2]}日`;
      getEightDayData(data)

      getDetailByDay()
      getMonthDate()
    }

    const getEightDayData = (data: string) => {
      // 得到当前时间
      let currentDate = new Date()
      let currentYear = currentDate.getFullYear()
      let currentMonth = currentDate.getMonth() + 1

      let dates = data.split('-')
      let year = Number(dates[0])
      let month = Number(dates[1])
      let day = Number(dates[2])
      // 得到这天是周几,
      // 注意 0 是周日, 0-6
      let weekDay = new Date(data).getDay()
      // 得到本月有几天
      let monthDay = new Date(year,month,0).getDate()

      // 一周7天
      let weekCount = 7;

      // 同年
      if(year === currentYear) {
        // 情况1 月份12 
        if(month === 12 && (day + (weekCount - weekDay)) > monthDay) {}
        // 情况2 月份1
        if(month === 1) {}

        // 情况3 选中这天是周日
        if(weekDay === 0) {
          
          if((day - weekCount) <= 0) {
            month = month - 1
            let preDay = new Date(year,month,0).getDate()
            day = preDay + (day - weekCount)
            startTime.value = `${year}-${month}-${day}`
            endTime.value = data
          } else {
            startTime.value = `${year}-${month}-${day - weekCount}`
            endTime.value = data
          }
          
        } else {
          // 情况4 处理不是周日
          

          if(day - weekDay <= 0) {
            let preDay = new Date(year,month - 1,0).getDate()
            startTime.value = `${year}-${month - 1}-${preDay + (day - weekDay)}`
            endTime.value = `${year}-${month}-${day + (weekCount - weekDay)}`

          } else {

            if(day + (weekCount - weekDay) > monthDay) {
              if(month === 12) {
                startTime.value = `${year}-${month}-${day - weekDay}`
                month = 1
                endTime.value = `${year + 1}-${month}-${day + (weekCount - weekDay) - monthDay}`
              } else {
                
                startTime.value = `${year}-${month}-${day - weekDay}`
                endTime.value = `${year}-${month + 1}-${day + (weekCount - weekDay) - monthDay}`
              }
            } else {
              startTime.value = `${year}-${month}-${day - weekDay}`
              endTime.value = `${year}-${month}-${day + (weekCount - weekDay)}`
            }
          }

          
        }


      }

      // 不同年
      if(year !== currentYear) {
        // 情况1 当前选中的是否是周日
        if(weekDay === 0) {
          // startTime.value
          if((day - weekCount) <= 0) {
            if(month === 1) {
              month = 12
              let preDay = new Date(year,month,0).getDate()
              day = preDay + (day - weekCount)
              startTime.value = `${year - 1}-${month}-${day}`
              endTime.value = data
            }
            // startTime.value = `${year}-${month}-${}`
          } else {
            startTime.value = `${year}-${month}-${day - weekCount}`
            endTime.value = data
          }
        } else {
          if(day - weekDay <= 0) {
            let preDay = new Date(year,month - 1,0).getDate()
            startTime.value = `${year}-${month - 1}-${preDay + (day - weekDay)}`
            endTime.value = `${year}-${month}-${day + (weekCount - weekDay)}`
          } else {
            
            if(day + (weekCount - weekDay) > monthDay) {
              if(month === 12) {
                startTime.value = `${year}-${month}-${day - weekDay}`
                year = year + 1
                month = 1
                endTime.value = `${year}-${month}-${day + (weekCount - weekDay) - monthDay}`
              } else {
                startTime.value = `${year}-${month}-${day - weekDay}`
                endTime.value = `${year}-${month + 1}-${day + (weekCount - weekDay) - monthDay}`
              }
            } else {
              startTime.value = `${year}-${month}-${day - weekDay}`
              endTime.value = `${year}-${month}-${day + (weekCount - weekDay)}`
            }
          }
        }

      }

    }

    const calendarData = reactive({
      ownSumMoney: 0,
      newAddOwnSumMoney: 0,
      topUpSumMoney: 0,
      payOrderSumMoney: 0,
      onlyTopUpBalanceSumMoney: 0,
    })
    const detailByDay = ref<any[]>([])

    const caledarList = ref([
      {
        title: '今日诊疗收款(元)',
        prop: 'orderTopSumMoney',
        todayNum: 0,
        yesterdayNum: 0,
        list: [
          {
            title: '订单（诊疗）收款',
            num: 0
          },
          {
            title: '订单（诊疗）退现',
            num: 0
          },
          // {
          //   title: '订单（诊疗）总收入 收款-退款',
          //   num: 0
          // }
        ]
      },
      {
        title: '今日欠款（元',
        prop: 'OwnSumMoney',
        todayNum: 0,
        yesterdayNum: 0,
        list: [
          {
            title: '新增欠款',
            num: 0,
            isShow: true,
            content: '新增待还款金额（财务应收款）'
          },
          {
            title: '收欠款',
            num: 0,
            isShow: true,
            content: '患者还欠费金额'
          },
          // {
          //   title: '欠款（新增欠款 - 收欠款）',
          //   num: 0,
          //   isShow: true,
          //   content: '患者在本店缴还他店欠费金额，可通过代收欠费报表查看明细'
          // }
        ]
      },
      {
        title: '今日现金流入（元)',
        prop: 'topUp',
        todayNum: 0,
        yesterdayNum: 0,
        list: [
          {
            title: '余额充值',
            num: 0,
            isShow: false,
            content: ''
          },
          {
            title: '订单付款',
            num: 0,
            isShow: false,
            content: ''
          },
          {
            title: '余额退现',
            num: 0,
            isShow: false,
            content: ''
          },
          {
            title: '订单退现',
            num: 0,
            isShow: false,
            content: ''
          }
        ]
      },
      {
        title: '今日诊疗服务收入（元）',
        prop: 'orderSumMoney',
        todayNum: 0,
        yesterdayNum: 0,
        list: [
          {
            title: '订单收入 （包含余额支付）',
            num: 0,
            isShow: false,
            content: ''
          },
          {
            title: '订单退款',
            num: 0,
            isShow: false,
            content: ''
          }
        ]
      }
    ])

    const getMonthDate = async() => {
      try{
        let res:any = await useRequest(`/statistical/pay/reconciliationForMonth`, {
          startTime: `${monthDateStart.value} 00:00:00`,
          endTime: `${monthDateEnd.value} 23:59:59`
        }, 'POST')
        let data = res.data;
        calendarData.ownSumMoney = data.ownSumMoney;
        calendarData.newAddOwnSumMoney = data.newAddOwnSumMoney;
        calendarData.topUpSumMoney = data.topUpSumMoney;
        calendarData.payOrderSumMoney = data.payOrderSumMoney;
        calendarData.onlyTopUpBalanceSumMoney = data.onlyTopUpBalanceSumMoney;
      } catch(e) {
        console.log(e)
      }
    }

    const getDetailByDay = async() => {
      try{
        let res:any = await useRequest(`/statistical/pay/reconciliationDetailByDay`, {
          startTime: `${startTime.value} 00:00:00`,
          endTime: `${endTime.value} 23:59:59`
        }, 'POST')
        let data = res.data
        detailByDay.value = res.data
        setEchartDate()
        filterData(data)
      }catch(e) {
        console.log(e)
      }
    }

    const filterData = (data: any) => {
      // 当前选中的这天的索引
      let res = data.findIndex((item:any) => {
        return item.dayStr === resultDate.value
      })
      let preIdx: any
      if(res === 0) {
        preIdx = 0
      } else {
        preIdx = res - 1
      }
      

      caledarList.value[0].todayNum = data[res].orderTopSumMoney
      caledarList.value[0].todayNum = data[preIdx].orderTopSumMoney
      caledarList.value[0].list[0].num = data[res].topUpForPayOrderSumMoney
      caledarList.value[0].list[1].num = data[res].orderRefundToMoneySumMoney

      caledarList.value[1].todayNum = data[res].OwnSumMoney
      caledarList.value[1].yesterdayNum = data[res].OwnSumMoney

      caledarList.value[1].list[0].num = data[res].newAddOwnSumMoney
      caledarList.value[1].list[1].num = data[res].putAwayOwnSumMoney


      caledarList.value[2].todayNum = data[res].topUp
      caledarList.value[2].yesterdayNum = data[preIdx].topUp
      caledarList.value[2].list[0].num = data[res].onlyTopUpBalanceSumMoney
      caledarList.value[2].list[1].num = data[res].topUpForPayOrderSumMoney
      caledarList.value[2].list[2].num = data[res].onlyBalanceToMoneySum
      caledarList.value[2].list[3].num = data[res].orderBalanceToMoneySum

      caledarList.value[3].todayNum = data[res].orderSumMoney
      caledarList.value[3].yesterdayNum = data[preIdx].orderSumMoney
      caledarList.value[3].list[0].num = data[res].orderPaySumMoney
      caledarList.value[3].list[1].num = data[res].orderRefundSMoney

    }


    return {
      isActive,
      getDay,
      type,
      caledarList,
      weekday,
      currentDate,
      ...toRefs(calendarData),
      setThousandBit
    }
  }
})
</script>

<style lang="scss" scoped>
.reconciliation-wrapper {
  display: flex;
  width: 100%;
  height: 100%;
  background-color: #fff;
  color: $primaryText;

  .left-info {
    .bill-info{
      font-size: 14px;
      color: $regularText;
      height: calc(100% - 300px);
      border-right: 1px solid #eceff1;
      box-sizing: border-box;
      div:nth-child(1) {
        font-weight: bold;
        padding-left: 15px;
        height: 40px;
        line-height: 40px;
      }
      .layout {
        padding-left: 15px;
        display: flex;
        height: 24px;
        line-height: 24px;
        & > span {
          display: inline-block;
        }
        & > span:nth-child(1) {
          width: 130px;
        }
        & > span:nth-child(2) {
          text-align: right;
          flex: 1;
          padding-right: 15px;
        }
      }
    }
  }

  .right-info {
    flex: 1;

    .calendar-detail {
      height: calc(100% - 260px);
      width: 100%;
      padding: 10px;
      box-sizing: border-box;

      .calendar-date {
        color: $primaryText;
        padding: 10px 0;
        & > span {
          font-size: 14px;
          
        }

        & > span:nth-child(2):hover, span:nth-child(3):hover {
          color: $mainColor;
          cursor: pointer;
          font-weight: bold;
        }
      }

      .calendar-content {
        display: grid;
        grid-template-columns: 1fr 1fr;
        grid-template-rows: 230px 230px;
        grid-gap: 10px;

      }
    }
  }
}
</style>